<?php
/**
 * Created by PhpStorm.
 * User: xing
 * Date: 2018/11/24
 * Time: 19:35
 */
namespace app\wechat\controller;

use EasyWeChat\Factory;
use taobao\AliOss;
use think\Db;
use think\Exception;

class Data extends Common {

    /**
     * 数据中心
     * @return \think\response\Json
     */
    public function dataCenter() {

        $currentCustomer = $this->request->currentCustomer;
        $startDate = $this->request->post("startDate");
        $endDate = $this->request->post("endDate");

        // 今天实时销售额
        $todaySaleAmt = $this->orderService
            ->getTodaySaleAmtByCustomerId($currentCustomer['id']);

        // 今天已赚
        $todayProfitAmt = $this->orderService
            ->getTodayProfitByCustomerId($currentCustomer['id']);

        // 今天UV访客总数
        $todayUvVisitorNum = $this->footprintLogService
            ->getVisitorStatistics($currentCustomer['id'], getCurrentDate());

        // 今天有效订单数
        $todayOrderCount = $this->orderService
            ->countTodayValidByCustomerId($currentCustomer['id']);

        // 今日客单价
        $todayAvgOrderAmt = "0.00";
        if ($todayOrderCount > 0) {
           $todayAvgOrderAmt = sprintf("%.2f",
               $todaySaleAmt/$todayOrderCount);
        }

        $returnData['today_data'] = [
            "total_sale_amt" => $todaySaleAmt,
            "total_profit_amt" => isNullOrEmpty($todayProfitAmt) ? "0.00" : $todayProfitAmt,
            "uv_visitor_num" => $todayUvVisitorNum['uv_visitor_num'],
            "total_order_count" => $todayOrderCount,
            "avg_order_amt" => $todayAvgOrderAmt
        ];

        // 统计历史数据
        $historyData = $this->customerEverydayStatisticsService
            ->sumHistoryDataByCustomerId($currentCustomer['id'], $startDate, $endDate);

        $uvVisitorNum = isNullOrEmpty($historyData['uv_visitor_num'])
            ? 0 : $historyData['uv_visitor_num'];

        $totalOrderCount = isNullOrEmpty($historyData['valid_order_count'])
            ? 0 : $historyData['valid_order_count'];

        $orderConversionRate = "0";
        if ($totalOrderCount > 0) {
           $orderConversionRate = round($totalOrderCount/$uvVisitorNum*100);
        }

        $returnData["history_data"] = [
            "total_sale_amt" => isNullOrEmpty($historyData['total_sale_amt'])
                ? "0.00" : $historyData["total_sale_amt"],
            "total_profit_amt" => isNullOrEmpty($historyData['total_profit_amt'])
                ? "0.00" : $historyData['total_profit_amt'],
            "uv_visitor_num" => $uvVisitorNum,
            "total_order_count" => $totalOrderCount,
            "avg_order_amt" => isNullOrEmpty($historyData['avg_order_amt'])
                ? "0.00" : $historyData['avg_order_amt'],
            "order_conversion_rate" => $orderConversionRate
        ];

        return successReturn($returnData);

    }

}